package bobochat.controller;


import bobochat.entity.FriendRequest;
import bobochat.entity.MyFriends;
import bobochat.entity.ResultData;
import bobochat.entity.Users;
import bobochat.service.UsersService;
import bobochat.util.FileUtils;
import bobochat.util.QRCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;
import java.util.UUID;



//@CrossOrigin
@RestController
public class UsersController<users, friendUsername, myUername, myUsername> {
    /**
     * @author bb
     * @create 2019-11-06 22:09
     */

    @Autowired
    private UsersService usersService;

    @GetMapping(value = "/getAllUsers", params = {"id", "name"})
    public List<Users> getAllUsers(String id, String name) {
        System.out.println("id:" + id + "   name:" + name);
        List<Users> users = usersService.queryAllUsers();
        return users;
    }

    /**
     * 用户注册
     * @param username
     * @param password
     * @return
     */

    @PostMapping(value = "/user", params = {"username", "password"})
    public ResultData register(String username, String password) {


        //判断username是否已经被注册
        Users checkUser=usersService.queryUserByUsername(username);
        if(checkUser!=null){
            return new ResultData("500","用户名已被注册");
        }

        Users users = new Users();
        //设置接收值
        users.setUsername(username);
        users.setPassword(password);


        //设置id
        users.setId(UUID.randomUUID().toString().replaceAll("", ""));

        //设置默认头像
        users.setFaceImage("/image/2.jpg");
        users.setFaceImageBig("/image/2.jpg");


        //设置二维码,地址为绝对地址
        String qrCodePath = "C:/Users/Bobo's master/Desktop/BoboChat/src/main/resources/static/image/qrcode" + "/" + username + "-qrcode.png";
        QRCodeUtils.createQRCode(qrCodePath, "BoboChat_qrcode:" + username);

        users.setQrcode("/image/qrcode/" + username + "-qrcode.png");
        usersService.register(users);

        System.out.println(users);


        return new ResultData("200","success");
    }

    /**
     * 用户登录
     * @param username
     * @param password
     * @return
     */
    @GetMapping(value = "/user/{username}")
    public ResultData login(@PathVariable("username") String username, String password) {
        Users users= new Users();

        //设置初始值
        users.setUsername(username);
        users.setUsername(password);
        Users resultUser = usersService.login(users);
        //若不为空则登录成功
        if (resultUser != null) {
            return new ResultData("200", "success",resultUser);
        } else {
            return new ResultData("500", "fail");
        }
    }

    /**
     * 根据用户更改昵称
     * @param id 用户id
     * @param nickname 用户昵称
     * @return
     */
    @PutMapping(value="/user/{id}")
    public ResultData updateNickname(@PathVariable("id")String id,String nickname ){

        //接收昵称
        Users users= new Users();
        users.setId(id);
        users.setNickname(nickname);

        //调用service层
        usersService.updateNickname(users);

        return  null;

    }

    /**
     * 根据用户id和旧密码去修改密码
     * @param id 用户id
     * @param oldPassword 旧密码
     * @param newPassword 新密码
     * @return
     */
    @PutMapping(value = "/user/{id}",params ={"oldpassword","newpassword"} )
    public ResultData updatePasswordById(@PathVariable("id") String id, String oldPassword, String newPassword) {
        Users users= new Users();
        users.setId(id);
        users.setPassword(oldPassword);
        usersService.updatePassword(users, newPassword);

        return null;
    }

    /**
     * 上传base64的图片字符串并更新头像
     * @param id
     * @param base64FaceImage
     * @return
     */
     @PutMapping("/user/{id}/faceImage")
     public ResultData uploadFaceImage(@PathVariable("id") String id,String base64FaceImage){
//         MultipartFile file= Base64DecodeMultipartFile.base64Convert(base64FaceImage);//转化为文件
         String path="C:/Users/Bobo's master/Desktop/BoboChat/src/main/resources/static/image/faceImage"+"/"+id+"-faceImage.png";
         try {
             FileUtils.base64ToFile(path,base64FaceImage);
         } catch (Exception e) {
             e.printStackTrace();
         }

         //将头像信息更新至数据库
         Users users = new Users();
         users.setId(id);
         users.setFaceImage(base64FaceImage);
         usersService.updateFaceImage(users);

         return null;
     }

    /**
     * 添加好友
     * @param friendUsername
     * @param myUsername
     * @return
     */
    @GetMapping("/user/{id}/username")
    public ResultData searchUserById(@PathVariable("friendUsername") String friendUsername,String myUsername){
        //若friendUsername和myUsername，则不允许添加
        if(friendUsername.equals(myUsername)) {
            return new ResultData("500", "不能添加自己为好友哦！");
        }
        //若好友不存在，返回提示信息
        Users checkFriend=usersService.queryUserByUsername(friendUsername);
        if(checkFriend==null){
            return new ResultData("500","用户不存在哦！");
        }
        //若已经为好友，则提示不能重复添加好友,再次查询数据表
        else if(friendUsername.equals(checkFriend)) {
            return new ResultData("500", "好友已存在，请不要重复添加哦！");
        }
        //若好友存在，则返回好友信息
        else{
            return new ResultData("200", "sucess", checkFriend);

        }
    }

    /**
     * 发送好友请求
     * @param myId
     * @param friendId
     * @return
     */
    @PostMapping("user/{myId}")
    public ResultData sendFriendRequest(@PathVariable("myId")String myId,String friendId){
        //把对应记录添加到friend_request表中

        FriendRequest friendRequest=new FriendRequest();
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString().replace("-", "");
        friendRequest.setId(id);
        friendRequest.setAcceptUserId(myId);
        friendRequest.setSendUserId(friendId);
        friendRequest.setSendRequestDateTime(new Date());
        usersService.sendFriendRequest(friendRequest);
        return  new ResultData("200","发送成功！");
    }


    /**
     * 获取所有好友请求
     * @param id 自己的id
     * @return
     */
    @GetMapping("user/{id}/friendRequest")
    public ResultData getAllFriendRequest(@PathVariable("id")String id){
      //查询friend_request表中对应accep_user_id为自己id的记录,并返回值
        FriendRequest friendRequest=usersService.queryUserRequestById(id);
        if(friendRequest!=null)
              return new ResultData("200","查询成功",friendRequest) ;
        else
            return new ResultData("500","您没有好友请求!");
    }

    /**
     * 通过或者忽略添加好友请求
     * @param myId
     * @param friendId
     * @param operate 操作1：通过；0：忽略
     */
    @PostMapping("user/{id}/operateRequest")
    public ResultData operateRequestById(@PathVariable("id")String myId,String friendId,String operate) {
        MyFriends myFriends=new MyFriends();
        myFriends.setMyUserId(myId);
        myFriends.setMyFriendsUserId(friendId);
        UUID uuid = UUID.randomUUID();
        String id = uuid.toString().replace("-", "");
        myFriends.setId(id);
        FriendRequest friendRequest=new FriendRequest();
        friendRequest.getSendUserId();
        friendRequest.getAcceptUserId();


        //判断operate的值
        if (operate.equals("1")) {
            usersService.addMyFriends(myFriends);
            return new ResultData("200","添加好友成功");
        } else if (operate.equals("0")) {

            usersService.deleteFriendRequest(friendRequest);
            return new ResultData("500","您已拒绝添加好友");
        } else {
            usersService.deleteFriendRequest(friendRequest);
            return new ResultData("500", "您已忽略他的请求！");
        }
    }


}